const app = getApp(),
  core = require('../../utils/core'),
  chatIM = require('../../utils/websocket.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    messageText: '',
    chatParams: {},
    userinfo: {},
    emotion_json: [], //表情
    loadingList: {
      total: 0,
      current_page: 0,
      last_page: 1,
      data: []
	},
	chatId:0,
    showEmoji: false,
	inputFocus: false,
	refreshSessionStatus: true,
    cursor: 0,
    scrollTop: 0,
	chatHeight: 0,
	isShowText:false,
	sentenceList:[]
  },
  //聊天滑动
  pageScrollToBottom() {
    const query = wx.createSelectorQuery().in(this);
    query.select('.scroll-wrap').boundingClientRect();
    query.select('.scroll-main').boundingClientRect();
    query.exec(res => {
      const scorllHeight = res[0].height;
      const listHeight = res[1].height;
      console.log(scorllHeight, listHeight);
      this.setData({
        scrollTop: listHeight
      });
    });
  },
  // 投递简历
  bindApply() {
    if (!app.getUserinfo(true)) {
      return;
	}
	let page = this;
	core.post({url: 'xilujob.job/chat_job',data:{receive_user_id: page.data.chatParams.receive_user_id},success:data=>{
		core.post({
			url: 'xilujob.job/apply',
			data: {
			  job_id: data.data
			},
			success: ret => {
			  wx.showModal({title: '提示',content: '投递成功',showCancel: false,});
				//发送投递成功的消息
				chatIM.sendMessage(page.data.chatParams.receive_user_id, ret.data.id,4);
			  page.pageScrollToBottom();
			  return false;
			},
			fail: ret => {
			  if (ret.code == -1) {
				wx.showModal({
				  title: '提示',
				  content: '需要先完善简历，现在要去吗？',
				  cancelText: '先看看',
				  confirmText: '立刻完善',
				  success: res => {
					if (res.confirm) {
					  wx.navigateTo({
						url: '/member/my_resume/my_resume'
					  });
					}
				  }
				});
				return false;
			  }
			}
		  });
	}
	})
  },
   //不感兴趣
   bindInterest() {
	let page = this;
    wx.showModal({
      title: '提示',
      content: '确定不感兴趣？',
      cancelText: '再聊聊',
      confirmText: '不感兴趣',
      success: res => {
        if (res.confirm) {
			chatIM.sendMessage(this.data.chatParams.receive_user_id, "暂时对您不感兴趣");
		}
		
      }
    });
  },
  //沟通职位
  bindCommunicateJob(){
	  wx.navigateTo({
		url: '/pages/chat_job/chat_job?receive_user_id='+this.data.chatParams.receive_user_id,
	  })
  },
  // 获取聊天列表
  msgList(res) {
    var loadingList = res.data;
    // 获取当前最顶部的VIEW_ID (注意是写在data.concat前面)


    if (this.data.loadingList.current_page > 1) {
      var now_loadingList_data = this.data.loadingList.data || [];
      var now_loadingList_data = now_loadingList_data.concat(loadingList.data);
      loadingList.data = now_loadingList_data;
    }
    this.setData({
      loadingList: loadingList
    });

    this.pageScrollToBottom();

    let receive_user_id = res.receive_user ? res.receive_user.id : 0;
    chatIM.wsSend({
      type: 'setread',
      receive_user_id: receive_user_id
    });
  },
  // 新消息
  newMsg(data) {
    if (data.to_uid != this.data.chatParams.receive_user_id && data.from_uid != this.data.chatParams.receive_user_id) {
      return false;
	}
    var loadingList = this.data.loadingList;
    var now_loadingList_data = loadingList.data || [];
    var ret = chatIM.handle_msg_data(data);
    var now_loadingList_data = now_loadingList_data.concat(ret.data);
    loadingList.data = now_loadingList_data;
    this.setData({
	  refreshSessionStatus:true,
      loadingList: loadingList
    });
    this.pageScrollToBottom();
    if (data.from_uid == this.data.chatParams.receive_user_id) {
      chatIM.wsSend({
        type: 'setread',
        receive_user_id: this.data.chatParams.receive_user_id
      });
    }
  },
  /*下拉刷新的回调 */
  downCallback() {
    //websocket获取列表
    chatIM.get_msg_list(this.data.chatParams.receive_user_id, 1);
  },
  //职位详情
  bindJobDetail(e){
	  //企业不可看职位详情
	  if(this.data.userinfo.group_id == 2){
		  return '';
	  }
	  let jobId = e.currentTarget.dataset.id;
	  wx.navigateTo({
		url: '/pages/jobs_detail/jobs_detail?id='+jobId,
	  })
  },
  onLoad: function (options) {
    var page = this;
    //表情
    this.setData({
      userinfo: app.getUserinfo(),
      emotion_json: app.globalData.chat_config.emoList
    })
    this.getOpenerEventChannel().on('chatTransfor', function (chatParams) {
      page.setData({
        chatParams: chatParams,
        refreshSessionStatus: chatParams.refresh_status || false
      })
      wx.setNavigationBarTitle({
        title: chatParams.to_username
      })
      //获取当前的聊天记录
      page.downCallback();
      //查询聊天进程与聊天记录
      if (chatParams.content) {
        chatIM.sendMessage(chatParams.receive_user_id, chatParams.content, chatParams.chat_type);
      }
    })
    app.eventBus.on('msg_list_callback', function (data) {
      page.msgList(data);
    })
    app.eventBus.on('new_msg_callback', function (data) {
	  page.setData({refreshSessionStatus: true});
      page.newMsg(data);
    })
	app.eventBus.on('del_session', function (data) {
		page.setData({refreshSessionStatus: true});
		//刷新列表
		wx.showModal({
			title:'提示',
			content: '设置成功',
			showCancel:false,
			success:function(){
				wx.navigateBack({});
			}
		})
	})
	//删除聊天记录
	app.eventBus.on("del_chat",function(data) {
		page.downCallback();
		return '';
		let loadingList = page.data.loadingList;
		let index = -1,index2 = -1;
		for(let i=0;i<loadingList.data.length;i++){
			for(let j=0;j<loadingList.data[i].data.length;j++){
				if(loadingList.data[i].data[j].id == data.id){
					index = i;
					index2 = j;
					break;
				}
			}
		}
		let lists = loadingList.data[index];
		if(index>=0 && index2>=0){
			lists.data.splice(index2,1);
			loadingList.data[index] = lists.data.length>0?lists:[]
		}
		page.setData({
			loadingList:loadingList,
			refreshSessionStatus:true
		})
	})
  },
  // 聚焦输入框
  inputOn(e) {
    this.setData({
      inputFocus: true,
      showEmoji: false
    })
    //console.log(this.data.keyboardH)
    //滑动在这编辑
    //this.mescroll.scrollTo(99999, 0);
  },
  // 失焦输入框
  inputOff() {
    this.inputFocus = false;
  },
  //常用语
  toggleUserText: function () {
    this.setData({
      isShowText: !this.data.isShowText,
      showEmoji: false
    })
    if(this.data.isShowText){
      this.getSentence()
    }
  },
  //常用语
  getSentence() {
    core.get({url: 'xilujob.sentence',loading: false,success: ret => {
        this.setData({
          sentenceList: ret.data
        })
      }
    });
  },
  chooseSentence(e){
	let index = e.currentTarget.dataset.index;
    let sentenceList = this.data.sentenceList;
    this.setData({
		messageText: sentenceList[index].name
    })
  },
  //表情
  showEmotion() {
    this.setData({
	  isShowText: false,
      showEmoji: !this.data.showEmoji
    })
  },
  //选择表情
  chooseEmoji(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      messageText: this.data.messageText + this.data.emotion_json[index].name
    })
  },
  // 输入内容
  bindInput(e) {
    this.setData({
      messageText: e.detail.value
    });
  },
  //发送
  bindSend() {
    let content = this.data.messageText;
    if (content.trim() == '') {
      wx.showToast({
        title: "发送内容不得为空",
        icon: 'none'
      });
      return false;
    }
    chatIM.sendMessage(this.data.chatParams.receive_user_id, content);
    this.setData({
      messageText: '',
      showEmoji: false
    });

    //this.mescroll.scrollTo(99999, 0);
  },
  //发送图片消息
  uploadImage() {
    let page = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        res.tempFiles.forEach(function (file) {
          core.uploadFile({
            filePath: file.tempFilePath,
            success(ret, response) {
              chatIM.sendMessage(page.data.chatParams.receive_user_id, ret.data.url, 2);
            }
          });
        });
      }
    })
  },
  //长按
  bindToggle(e){
	let index = e.currentTarget.dataset.index;
	let index2 = e.currentTarget.dataset.index2;
	let loadingList = this.data.loadingList;
	this.setData({chatId:loadingList.data[index].data[index2].id})
  },
  //消息撤回
  revoke(e){
	let index = e.currentTarget.dataset.index;
	let index2 = e.currentTarget.dataset.index2;
	let loadingList = this.data.loadingList;
	let id = loadingList.data[index].data[index2].id;
	chatIM.wsSend({
        type: 'delchat',
		receive_user_id: this.data.chatParams.receive_user_id,
		content:id
	  });
  },
  //面试邀请
  bindCreateInterview() {
    if (app.getUserinfo().group_id != 2) {
      wx.showToast({title: '请切换到公司身份',icon: 'none'});
      return;
    }
    let resumeId = this.data.chatParams.resume_id;
    core.post({
      url: 'xilujob.resume/get_interview',
      data: {
        resume_id: resumeId
      },
      success: ret => {
        wx.navigateTo({
          url: '/pages/interview_take/interview_take',
          events: {
            dataTransfer: data => {
              this.setData({
                isInterviewing: true
              });
            }
          },
          success: res => {
            res.eventChannel.emit('dataTransfer', {
              resume: ret.data
            });
          }
        });
      },
      fail: ret => {
        if (ret.code == -1) {
          this.setData({
            actionTipMsg: ret.msg
          });
          return false;
        }
      }
    });

  },

  onUnload: function () {
    app.eventBus.off('new_msg_callback')
    app.eventBus.off('msg_list_callback');
    app.eventBus.off('del_session');
    app.eventBus.off('del_chat');
    if (this.data.refreshSessionStatus) {
	  this.getOpenerEventChannel().emit("refreshSession",{});
	  app.eventBus.emit("refresh_session",{});
    }
  },
  //拒绝面试
  bindRejectInterview(e) {
    var that = this;
	let index = e.currentTarget.dataset.index;
	let index2 = e.currentTarget.dataset.index2;
	let loadingList = this.data.loadingList;
	let id = loadingList.data[index].data[index2].message_text.id;
    wx.showModal({
      title: '提示',
      content: '确认拒绝面试？',
      success: res => {
        if (res.confirm) {
          core.post({
            url: 'xilujob.job_interview/multi_status/interview_id/' + id,
            data: {status: 1},
            success: ret => {
				loadingList.data[index].data[index2].message_text.status = 1;
              that.setData({
                loadingList
              });
            }
          });
        }
      }
    })
  },
  bindAcceptInterview(e) {
    let that = this;
	let index = e.currentTarget.dataset.index;
	let index2 = e.currentTarget.dataset.index2;
	let loadingList = this.data.loadingList;
	let id = loadingList.data[index].data[index2].message_text.id;
    wx.showModal({
      title: '提示',
      content: '确认接受面试？',
      success: res => {
        if (res.confirm) {
          core.post({
            url: 'xilujob.job_interview/multi_status/interview_id/' + id,
            data: {
              status: 2
            },
            success: ret => {
				loadingList.data[index].data[index2].message_text.status = 2;
				that.setData({
				  loadingList
				});
            }
          });
        }
      }
    })
  },
})
